//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/my/rank_type_enum.dart';
import 'package:hktk_app/ienum/subject/collection_type_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/home/column_model.dart';
import 'package:hktk_app/model/my/chaper_tree_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/mine/view_chapter_expandable_widget.dart';
import 'package:hktk_app/widget/mine/view_chapter_show_widget.dart';

/// 我的错题/收藏章节显示页面
class ViewChapterPage extends StatefulWidget {
  /// 相关信息
  final ColumnModel tabModel;

  /// 类型，错题/收藏
  final RankTypeEnum rankType;

  const ViewChapterPage({
    super.key,
    required this.tabModel,
    required this.rankType,
  });

  @override
  State<ViewChapterPage> createState() => _ViewChapterPageState();
}

class _ViewChapterPageState extends State<ViewChapterPage> {
  late BuildContext _context;

  /// 初始化方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关数据
  late List<ChapterTreeModel> _list;

  /// 监听器
  late StreamSubscription<EventWrongCollectDelete> _eventWrong;

  @override
  void initState() {
    super.initState();
    debugPrint("viewChapterPage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _list = [];
    _futureInit = _initData();

    // 监听记录清除通知
    _eventWrong = eventBus.on<EventWrongCollectDelete>().listen((event) {
      debugPrint("viewChapterPage 页面 -> 错题/收藏记录清除通知监听执行 ===> ");
      setState(() {
        _list = [];
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("viewChapterPage 页面 -> dispose 方法执行 ===> ");
    debugPrint("");
    _eventWrong.cancel();
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("viewChapterPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder:
          (BuildContext context, AsyncSnapshot<Map<String, dynamic>> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      DataModel dataModel = dataUtilComm.dataModel;
      _list = await MyDao.chapterRecordsTree(
        industryCode: dataModel.industryId,
        examId: dataModel.examId,
        categoryId: dataModel.categoryId,
        collectionType: CollectionTypeEnum.chapter,
        type: widget.rankType,
        industryName: dataModel.industryName,
        examName: dataModel.examName,
        categoryName: dataModel.categoryName,
        columnId: widget.tabModel.id!,
      );

      map["suc"] = true;
    } catch (e) {
      debugPrint("viewChapterPage 页面 -> 初始化数据方法发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("viewChapterPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 内容显示方法
  _content() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 24),
      padding: EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: colorWhite1,
        borderRadius: BorderRadius.circular(20),
      ),
      child: _showConItem(),
    );
  }

  /// 内容显示
  _showConItem() {
    if (_list.isNotEmpty) {
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: _list.length,
        ),
      );
    } else {
      return showNoData(
        style: FontUtil.fontGrey2(28, fontWeight: FontWeight.w500),
      );
    }
  }

  /// 内容显示组件
  Widget? _itemBuilder(BuildContext context, int index) {
    ChapterTreeModel model = _list[index];
    if (model.leaf!) {
      // 没有子章节
      return ViewChapterShowWidget(
        chapterModel: model,
        rankType: widget.rankType,
      );
    } else {
      return ViewChapterExpandableWidget(
        chapterModel: model,
        columnId: widget.tabModel.id!,
        rankType: widget.rankType,
        opening: index == 0,
      );
    }
  }
}
